import {createRouter, createWebHistory} from 'vue-router'
import {ElMessage} from "element-plus";
const Login = () => import('@/views/Login/login.vue')
const Register = () => import('@/views/Register/register.vue')
const Home = () => import('@/views/Home/home.vue')
const homepage = () => import('@/views/Home/homepage.vue')

const routes = [
    {
        path: '/login',
        name: 'login',
        component: Login,
    },
    {
        path: '/register',
        name: 'register',
        component: Register
    },
    {
        path: '/',
        component: Home,
        redirect: '/login',//首页默认重定向到登录页
        children: [
            {
                path: 'home',
                name: 'home',
                component: homepage,
                meta: {
                    isLoggedIn: true,
                }
            },
        ]
    },
]
const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    if (to.meta.isLoggedIn) {
        try {
            let token = JSON.parse(localStorage.getItem('userInfo')).userInfo.token
            if (!token) {
                ElMessage.warning("请先登录！")
                next('/login')
            } else {
                next()
            }
        } catch (error) {
            ElMessage.warning("请先登录！")
            next('/login')
        }
    } else {
        next()
    }
})
export default router